#include "prescriptionwidget.h"
#include "ui_prescriptionwidget.h"
#include "medicineselectdialog.h"
#include "../../network/networkclient.h"
#include <QMessageBox>
#include <QDateTime>
#include <QPushButton>
#include <QHBoxLayout>
#include <QFormLayout>

PrescriptionWidget::PrescriptionWidget(const Doctor& doctor, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PrescriptionWidget),
    m_doctor(doctor),
    m_hasPatient(false) {
    ui->setupUi(this);
    
    // 添加"选择药物"按钮到药品输入框旁边
    addMedicineSelectButton();
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PrescriptionWidget::onMessageReceived);
}

PrescriptionWidget::PrescriptionWidget(const Doctor& doctor, const Patient& patient, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PrescriptionWidget),
    m_doctor(doctor),
    m_hasPatient(true) {
    ui->setupUi(this);
    
    // 添加"选择药物"按钮
    addMedicineSelectButton();
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PrescriptionWidget::onMessageReceived);
    
    setupPatientInfo(patient);
}

PrescriptionWidget::PrescriptionWidget(const Doctor& doctor, const Patient& patient, int appointmentId, int recordId, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PrescriptionWidget),
    m_doctor(doctor),
    m_hasPatient(true),
    m_appointmentId(appointmentId) {
    ui->setupUi(this);
    
    // 添加"选择药物"按钮
    addMedicineSelectButton();
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PrescriptionWidget::onMessageReceived);
    
    setupPatientInfo(patient);
    
    // 自动填充病历ID
    if (recordId > 0) {
        ui->recordIdEdit->setText(QString::number(recordId));
    }
}

void PrescriptionWidget::addMedicineSelectButton() {
    // 在药品输入框下方添加按钮
    QFormLayout* formLayout = qobject_cast<QFormLayout*>(this->layout());
    if (formLayout) {
        QPushButton* selectMedicineBtn = new QPushButton("📋 从药物表选择");
        selectMedicineBtn->setStyleSheet(
            "QPushButton { background-color: #409EFF; color: white; padding: 8px 16px; "
            "border-radius: 4px; font-weight: bold; min-height: 30px; }"
            "QPushButton:hover { background-color: #66B1FF; }");
        connect(selectMedicineBtn, &QPushButton::clicked, this, &PrescriptionWidget::onSelectMedicineClicked);
        
        // 在第3行（药品名称下方）插入按钮
        formLayout->insertRow(3, "", selectMedicineBtn);
    }
}

void PrescriptionWidget::setupPatientInfo(const Patient& patient) {
    // 自动填充患者ID
    ui->patientIdEdit->setText(QString::number(patient.id));
    ui->patientIdEdit->setReadOnly(true);
    
    // 显示患者基本信息
    setWindowTitle(QString("为患者 %1 开具处方").arg(patient.realName));
}

PrescriptionWidget::~PrescriptionWidget() {
    delete ui;
}

void PrescriptionWidget::on_saveButton_clicked() {
    qDebug() << "=== 开始保存处方 ===";
    
    // 验证患者ID
    QString patientIdText = ui->patientIdEdit->text();
    qDebug() << "患者ID:" << patientIdText;
    if (patientIdText.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入患者ID");
        return;
    }
    
    // 验证病历ID
    QString recordIdText = ui->recordIdEdit->text();
    int recordId = recordIdText.toInt();
    qDebug() << "病历ID文本:" << recordIdText << "转换为整数:" << recordId;
    
    if (recordIdText.isEmpty() || recordId == 0) {
        qDebug() << "病历ID验证失败";
        QMessageBox::warning(this, "提示", "请输入有效的病历ID\n\n提示：需要先创建病历，然后才能开具处方");
        return;
    }
    qDebug() << "病历ID验证通过";

    
    // 验证必填字段
    if (ui->medicationsEdit->toPlainText().trimmed().isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入药品名称");
        return;
    }
    
    if (ui->dosageEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入药品剂量");
        return;
    }
    
    if (ui->usageEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入用法");
        return;
    }
    
    if (ui->frequencyEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入用药频率");
        return;
    }
    
    Prescription prescription;
    prescription.medicalRecordId = ui->recordIdEdit->text().toInt();
    prescription.patientId = ui->patientIdEdit->text().toInt();
    prescription.doctorId = m_doctor.id;
    prescription.appointmentId = m_appointmentId;  // 设置预约ID
    prescription.prescriptionTime = QDateTime::currentDateTime();
    prescription.medications = ui->medicationsEdit->toPlainText();
    prescription.dosage = ui->dosageEdit->text();
    prescription.usage = ui->usageEdit->text();
    prescription.frequency = ui->frequencyEdit->text();
    prescription.days = ui->daysSpinBox->value();
    prescription.notes = ui->notesEdit->toPlainText();
    
    QJsonObject request = prescription.toJson();
    NetworkClient::instance().sendRequest(MSG_CREATE_PRESCRIPTION, request);
}

void PrescriptionWidget::on_clearButton_clicked() {
    ui->recordIdEdit->clear();
    ui->patientIdEdit->clear();
    ui->medicationsEdit->clear();
    ui->dosageEdit->clear();
    ui->usageEdit->clear();
    ui->frequencyEdit->clear();
    ui->daysSpinBox->setValue(7);
    ui->notesEdit->clear();
}

void PrescriptionWidget::on_backButton_clicked() {
    // 如果是从患者详情页进入的，发送返回信号
    if (m_hasPatient) {
        emit backToPatientDetail();
    }
}

void PrescriptionWidget::onSelectMedicineClicked() {
    // 打开药物选择对话框
    MedicineSelectDialog dialog(this);
    
    if (dialog.exec() == QDialog::Accepted) {
        Medicine medicine = dialog.getSelectedMedicine();
        
        // 自动填充药物信息
        ui->medicationsEdit->setPlainText(medicine.name);
        
        // 填充用法用量（如果有）
        if (!medicine.usageInstruction.isEmpty()) {
            // 解析用法用量，尝试分离剂量和用法
            ui->dosageEdit->setText(medicine.specification);  // 使用规格作为剂量
            ui->usageEdit->setText(medicine.usageInstruction);
            ui->frequencyEdit->setText("一日三次");  // 默认频率
        }
        
        // 填充注意事项到备注
        if (!medicine.precautions.isEmpty()) {
            QString currentNotes = ui->notesEdit->toPlainText();
            if (!currentNotes.isEmpty()) {
                currentNotes += "\n\n";
            }
            currentNotes += "【注意事项】\n" + medicine.precautions;
            ui->notesEdit->setPlainText(currentNotes);
        }
        
        QMessageBox::information(this, "提示", 
            QString("已选择药物：%1\n规格：%2\n\n"
                    "请根据患者实际情况调整剂量、用法和频率。")
            .arg(medicine.name, medicine.specification));
    }
}

void PrescriptionWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_CREATE_PRESCRIPTION_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "处方开具成功");
            on_clearButton_clicked();
            emit prescriptionCreated();  // 发送处方创建成功信号
        } else {
            QMessageBox::warning(this, "失败", data["error"].toString());
        }
    }
}

